<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable
      @register="registerTable"
      @row-contextmenu="handleContext"
      @row-db-click="rowDbClick"
    >
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <Select
          v-model:value="beforeDate"
          :options="dateOptions"
          @change="handleChange"
          style="width: 100px; height: 25px"
        />
        <!-- <a-checkbox v-model:checked="hideInvalidDoc">隐藏失效文档</a-checkbox>
        <a-checkbox v-model:checked="showLastVer">显示最新版本文档</a-checkbox> -->
      </template>
    </BasicTable>
    <BasicModal
      :title="t('问题反馈')"
      @register="registerModal"
      @ok="handleQusSubmit"
      :minHeight="300"
      :width="600"
      :forceRender="true"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsPlmDocPLMDocDistributionList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, onMounted, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import {
    ActionItem,
    BasicTable,
    FormProps,
    TableCustomRecord,
    useTable,
  } from '/@/components/Table';
  import { customListData, listSet, encodeDocInfo } from '/@/api/test/testData';
  import { schemasData, tabConfigData, fieldMapToTimeData } from '/@/utils/custom';
  import { useContextMenu } from '/@/hooks/web/useContextMenu';
  import { encryptRSA } from '/@/utils/encrypt/RSA';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useGo } from '/@/hooks/web/usePage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useRouter } from 'vue-router';
  import { Select } from '/@/components/Form/index';
  import { sendQusData } from '/@/api/plm/doc/commons';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  const { ctxAdminPath } = useGlobSetting();
  let router = useRouter();
  const { userInfo } = useUserStore();
  const go = useGo();

  const { t } = useI18n('plm.doc.pLMDocDistribution');
  const { createMessage, showMessage } = useMessage();

  const [createContextMenu] = useContextMenu();

  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('doc_021管理'),
  };

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  let title = ref('');
  let fieldMapToTime = ref<any>([]);

  let hideInvalidDoc = ref(false);
  let showLastVer = ref(false);
  let beforeDate = ref('1');
  let dateOptions = [
    { label: '全部', value: '0' },
    { label: '近1天', value: '1' },
    { label: '近7天', value: '7' },
    { label: '近30天', value: '30' },
    { label: '近3个月', value: '90' },
  ];

  watch(
    () => hideInvalidDoc.value,
    async () => {
      reload();
    },
  );

  watch(
    () => showLastVer.value,
    async () => {
      reload();
    },
  );

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 8, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
    fieldMapToTime: [['outputtime', ['beginTime', 'endTime']]],
  });

  const actionColumn: BasicColumn = {
    width: 80,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('问题反馈'),
        onClick: handleQesForm.bind(this, record),
      },
    ],
  };

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('接收人'),
      field: 'receiver',
      fieldLabel: 'receiveName',
      component: 'ListSelect',
      componentProps: {
        selectType: 'userSelect',
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('问题描述'),
      field: 'quesData',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 200,
        rows: 10,
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
  ];

  onMounted(async () => {
    setTimeout(async () => {
      const res = await listSet({ viewCode: 'doc_myDoc_list_01' });
      title.value = res.layVoucherView.name;
      layVoucherView.value = res.layVoucherView;
      searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);
      /*   searchForm.value.fieldMapToTime = fieldMapToTimeData(
        layVoucherView.value.listQuery.queryCols,
      ); */
      tableColumns.value = layVoucherView.value.flistTabCols; //表格表头
      butData.value = layVoucherView.value.headBtns; //表格右上角按钮

      actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

      listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
      setProps({
        ...listTabConfig.value,
        api: customListData,
        beforeFetch: (params) => {
          params.url = listTabConfig.value.api;
          params.beforeDate = beforeDate.value;
          // params.isShowLatestVer = showLastVer.value ? '1' : '0';
          return params;
        },
        rowClassName: (record: TableCustomRecord<any>, index: number) => {
          return 'red';
        },
      });
      if (!listTabConfig.value.immediate) {
        reload();
      }
    }, 500);
  });

  const [registerTable, { reload, setProps }] = useTable({
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    actionColumn: actionColumn,
  });
  const [registerModal, { openModal, setModalProps, closeModal }] = useModal();
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const picTypes = ['png', 'jpg', 'jpeg', 'gif', 'txt', 'mp4'];

  let loading = ref(false);
  let absolute = ref(false);
  let tip = ref('加载中...');
  let quesData = ref('');
  let currentDocCode = ref('');
  let currentDocVer = ref('');
  let currentDocName = ref('');

  async function handlePreview(record: Recordable, bviewPdf: String) {
    const url =
      ctxAdminPath +
      '/plm/file/previewNew?docCode=' +
      record.plmDocInfo.cdocumentid +
      '&docVer=' +
      record.plmDocInfo.cdocumentver +
      '&docType=' +
      record.plmDocInfo.cdformat;
    let layerWidth = $(window).width();
    if (layerWidth < 800) {
      layerWidth -= 15 * 2;
    } else {
      layerWidth -= 100 * 2;
    }
    let layerHeight = $(window).height();
    if (layerHeight < 500) {
      layerHeight -= 15 * 2;
    } else {
      layerHeight -= 25 * 2;
    }
    if (picTypes.includes(record.plmDocInfo.cdformat)) {
      window.layer.open({
        type: 2,
        maxmin: true,
        shadeClose: false, // 点击背景关闭
        title: false,
        area: [layerWidth + 'px', layerHeight + 'px'],
        method: 'get',
        content: url,
      });
      return;
    }
    const params = {
      docCode: record.plmDocInfo.cdocumentid,
      docVer: record.plmDocInfo.cdocumentver,
      docType: bviewPdf === '1' ? 'pdf' : record.plmDocInfo.cdformat,
      bviewPdf: bviewPdf,
    };
    go({
      path: '/plm/doc/pLMDocInfo/fileView',
      query: {
        params: encryptRSA(JSON.stringify(params)),
      },
    });
  }

  function handleContext(record: any, row: Number, e: MouseEvent) {
    createContextMenu({
      event: e,
      items: [
        {
          label: '浏览',
          handler: () => {
            handlePreview(record, '0');
          },
          disabled: !(
            record.privName === '浏览' ||
            record.privName === '控件浏览' ||
            record.privName === '浏览源文件' ||
            record.privName === '下载'
          ),
        },
        {
          label: '浏览PDF',
          handler: () => {
            handlePreview(record, '1');
          },
          disabled: !(
            record.privName === '浏览' ||
            record.privName === '控件浏览' ||
            record.privName === '浏览源文件' ||
            record.privName === '浏览PDF' ||
            record.privName === '下载PDF' ||
            record.privName === '下载'
          ),
        },
        {
          label: '下载',
          handler: () => {
            downloadByUrl({
              url: `/rest/preview/view/${record.plmDocInfo.cdocumentid}/${record.plmDocInfo.cdocumentver}/download`,
            });
          },
          disabled: !(record.privName === '下载源文件' || record.privName === '下载'),
        },
        {
          label: '下载PDF',
          handler: () => {
            downloadByUrl({
              url: `/rest/preview/viewPdf/${record.plmDocInfo.cdocumentid}/${record.plmDocInfo.cdocumentver}/download`,
            });
          },
          disabled: !(record.privName === '下载PDF' || record.privName === '下载'),
        },
      ],
    });
  }

  function handleChange() {
    console.log('handleChange', beforeDate.value);
    reload();
  }

  async function rowDbClick(record) {
    if (picTypes.includes(record.cdformat)) {
      if (
        !(
          record.privName === '浏览' ||
          record.privName === '控件浏览' ||
          record.privName === '浏览源文件' ||
          record.privName === '下载'
        )
      ) {
        createMessage.error('无预览权限！');
        return;
      } else {
        handlePreview(record, '0');
        return;
      }
    }
    if (!picTypes.includes(record.cdformat)) {
      if (
        !(
          record.privName === '浏览' ||
          record.privName === '控件浏览' ||
          record.privName === '浏览源文件' ||
          record.privName === '浏览PDF' ||
          record.privName === '下载PDF' ||
          record.privName === '下载'
        )
      ) {
        createMessage.error('无预览权限！');
        return;
      } else {
        handlePreview(record, '1');
        return;
      }
    }
  }

  function handleQesForm(record) {
    quesData.value = '';
    currentDocCode.value = record.plmDocInfo?.cdocumentid;
    currentDocVer.value = record.plmDocInfo?.cdocumentver;
    currentDocName.value = record.plmDocInfo?.cdocumentname;
    openModal();
    setFieldsValue({
      receiver: record.creatorid,
      receiveName: record.creator?.cpersonname,
    });
  }

  async function handleQusSubmit() {
    try {
      const data = await validate();
      console.log(data);
      setModalProps({ confirmLoading: true });
      const params = {};
      const reqData = {
        sender: userInfo?.userCode,
        receiver: data.receiver,
        subject: '文档错误',
        content: `文档如下：
  文档名为：（${currentDocName.value}）编码：（${currentDocCode.value}）版本：（${currentDocVer.value}）的文档。

  反馈内容如下：
      ${data.quesData}
                 `,
      };
      console.log(params);
      const { message } = await sendQusData(params, reqData);
      showMessage(message);
      setTimeout(closeModal);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
